# coding=utf-8
"""
用来管理selenium常用操作的工具类
"""
import time

from get_chrome_driver import GetChromeDriver
from selenium import webdriver
from selenium.common import WebDriverException
from selenium.webdriver.chrome.options import Options
import os

from selenium.webdriver.chrome.service import Service


class SeleniumUtils:
    driver_dir = os.path.join(os.getcwd(), "driver")

    @staticmethod
    def get_chrome_driver(options: Options = None) -> webdriver:
        driver_path = os.path.join(SeleniumUtils.driver_dir, "chromedriver.exe")
        service = Service(executable_path=driver_path)
        try:
            if os.path.exists(driver_path):
                # 驱动已经下载,使用安装好的驱动
                print("驱动已经下载,测试能否正常使用")
                driver = webdriver.Chrome(options=options, service=service)
                return driver
            # options.binary_location = driver_path
            # 如果能够获取到driver,即使用selenium的driver
            print("尝试使用selenium获取驱动,此过程可能持续几分钟,耐心等待")
            driver = webdriver.Chrome(options=options)
            return driver
        except WebDriverException as e:
            print("使用系统驱动失败,检测同目录依赖下载情况")
            # 检查驱动是否存在
            print("正在自动下载所需驱动,此过程可能会花费几分钟,请耐心等待")
            get_driver = GetChromeDriver()
            get_driver.install(output_path=SeleniumUtils.driver_dir)
            driver = webdriver.Chrome(options=options, service=service)
            return driver


if __name__ == '__main__':
    bro = SeleniumUtils.get_chrome_driver()
    bro.get("https://google.com")
    time.sleep(3)
    bro.close()
